package impl

import (
	"context"
	"errors"
	"gitee.com/hexug/vblog/tree/master/api/apps/post"
	"gitee.com/hexug/vblog/tree/master/api/apps/tag"
	"gitee.com/hexug/vblog/tree/master/api/logger"
	"gitee.com/hexug/vblog/tree/master/api/validate"
	"gorm.io/gorm"
)

// CreateTag 创建标签
func (i *impl) CreateTag(ctx context.Context, request *tag.CreateTagRequest) (*tag.Tag, error) {
	if err := validate.V().Struct(request); err != nil {
		return nil, err
	}
	req := post.NewDeleteOrGetBlogRequest(request.BlogId)
	_, err := i.Blog.GetDetailsBlog(ctx, req)
	if err != nil {
		return nil, err
	}
	t, err := tag.NewTag(request)
	if err != nil {
		return nil, err
	}
	res := i.Db.WithContext(ctx).Create(t)
	if res.Error != nil {
		return nil, res.Error
	}
	return t, nil
}

// UpdateTag 更新标签
func (i *impl) UpdateTag(ctx context.Context, request *tag.UpdateTagRequest) (*tag.Tag, error) {
	if err := validate.V().Struct(request); err != nil {
		return nil, err
	}
	var t *tag.Tag
	err := i.Db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		res := tx.Table("tags").Where("id=?", request.Id).Delete(&tag.Tag{})
		if res.Error != nil {
			return res.Error
		}
		if res.RowsAffected == 0 {
			return errors.New("未找到对应的标签")
		}
		var err error
		t, err = i.CreateTag(ctx, request.CreateTagRequest)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return t, nil
}

// DeleteTag 删除标签
func (i *impl) DeleteTag(ctx context.Context, request *tag.DeleteOrGetTagRequest) (*tag.TagsList, error) {
	db := i.Db.Table("tags").WithContext(ctx)
	if *request == *tag.NewDeleteOrGetTagRequest() {
		logger.L().Error("参数为空！")
		return nil, errors.New("参数为空！")
	}
	tags, err := i.GetTag(ctx, request)
	if err != nil {
		return nil, err
	}
	if request.Id != "" {
		db = db.Where("id=?", request.Id)
	}
	if len(*request.BlogIds) != 0 {
		db = db.Where("blog_id in ?", *request.BlogIds)
	}
	res := db.Delete(&tag.Tag{})
	if res.Error != nil {
		logger.L().Error(res.Error.Error())
		return nil, res.Error
	}
	return tags, nil
}

// GetTag 查询标签
func (i *impl) GetTag(ctx context.Context, request *tag.DeleteOrGetTagRequest) (*tag.TagsList, error) {
	db := i.Db.Table("tags").WithContext(ctx)
	if *request == *tag.NewDeleteOrGetTagRequest() {
		logger.L().Error("参数为空！")
		return nil, errors.New("参数为空！")
	}
	if request.Id != "" {
		db = db.Where("id=?", request.Id)
	}
	if request.BlogIds != nil {
		db = db.Where("blog_id in ?", *request.BlogIds)
	}
	tags := tag.NewTagsList()
	res := db.Find(&tags.Items)
	if res.Error != nil {
		logger.L().Error(res.Error.Error())
		return nil, res.Error
	}
	if res.RowsAffected == 0 {
		return nil, errors.New("未找到标签。")
	}
	tags.Total = res.RowsAffected
	return tags, nil
}
